
    /**  
    * @Title: DataSourceAspect.java
    * @Package com.wq.datasource
    * @Description: 
    * @author likai
    * @date 2017年4月24日
    * @version V1.0  
    */
    
package com.frames.datasource;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 有{@link com.wangzhixuan.commons.annotation.DataSourceChange}注解的方法，调用时会切换到指定的数据源
 *
 * @author tanghd
 */
public class DataSourceAspect{
	public static Logger log = LoggerFactory.getLogger(DataSourceAspect.class);

    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
    	log.info("---------------------动态数据源切换开始----------------------");
        Object retVal = null;
		Signature s = pjp.getSignature();
		MethodSignature ms = (MethodSignature)s;
		Method m = ms.getMethod();
		DataSource dataSource=m.getAnnotation(DataSource.class);
       try {
            if (null != dataSource) {
            	//有注解
                if (dataSource.write()) {
                    ChooseDataSource.putDataSource(ChooseDataSource.WRITE);//写库
                } else {
                	ChooseDataSource.putDataSource(ChooseDataSource.READ);//读库
                }
            }else {
            	//无注解，使用默认读库
            	ChooseDataSource.putDataSource(ChooseDataSource.WRITE);;
			}
            retVal = pjp.proceed();
            log.info("---------------------动态数据源切换结束----------------------");
        } catch (Throwable e) {
            throw new RuntimeException("数据源切换错误");
        }
        return retVal;
    }
}
